from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from apps.drf_test_0Django原始restful.models import BookinfoModels
from apps.drf_test_4_listView.serializer import BookInfoSerializer


class BookInfoListApiViews(APIView):
    """
    书籍列表视图
    """
    def get(self,request):
        """
        获取所有书籍
        :param request:
        :return:
        """
        # 1、获取书籍列表
        books = BookinfoModels.objects.all()
        # 2、创建序列化器，序列化数据
        serializer = BookInfoSerializer(instance=books,many=True)
        return Response(serializer.data,status=status.HTTP_200_OK)


    def post(self,request):
        """
        新建书籍
        :param request:
        :return:
        """
        # 1、获取参数
        res = request.data
        # 2、创建序列化器
        serializer = BookInfoSerializer(data=res)
        # 3、校验
        serializer.is_valid(raise_exception=True)
        # 4、入库
        serializer.save()
        return Response(serializer.data,status=status.HTTP_201_CREATED)


class BookInfoDetailApiView(APIView):
    """
    书籍详情
    """
    def get(self,request,book_id):
        """
        获取单个书籍详情
        :param request:
        :param book_id: 书籍id
        :return:
        """
        # 1、获取单个书籍
        book = BookinfoModels.objects.get(id = book_id)
        # 2、创建序列化器
        serializer = BookInfoSerializer(instance=book)
        return Response(serializer.data,status=status.HTTP_200_OK)

    def put(self,request,book_id):
        """
        修改书籍
        :param request:
        :param book_id:
        :return:
        """
        # 1、获取要修改的书籍对象
        book = BookinfoModels.objects.get(id = book_id)
        # 2、获取修改的内容
        res = request.data
        # 3、创建序列化器
        serializer = BookInfoSerializer(instance=book,data=res)
        # 4、校验
        serializer.is_valid(raise_exception=True)
        # 5、入库
        serializer.save()
        return Response(serializer.data,status=status.HTTP_201_CREATED)

    def delete(self,request,book_id):
        """
        删除书籍
        :param request:
        :param book_id:
        :return:
        """
        # 1、获取要删除的书籍
        book = BookinfoModels.objects.get(id = book_id)
        # 2、删除书籍
        book.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

